const Product = require('../models/Product');
const {
   numericHandler,
   fuzzySearchHandler,
   extendQuery,
} = require('../utils/extend-query');
const pageHandler = require('../utils/page-handler');

const formatHandler = (values, _default = '') =>
   values ? values.split(',').join(' ') : _default;

const getProducts = async (req, res) => {
   const [skip, limit] = pageHandler(req.query);

   const products = await Product.find(
      extendQuery(req.query, {
         ...fuzzySearchHandler('name', req.query.name),
         ...numericHandler(req.query.numeric),
      })
   )
      .sort(formatHandler(req.query.sort))
      .select(formatHandler(req.query.fields, '_id name price company'))
      .skip(skip)
      .limit(limit);
   const total = await Product.countDocuments();

   res.data({
      list: products,
      total,
   });
};
const getProductsStatic = async (req, res) => {
   res.ok('getProductsStatic');
};
module.exports = {
   getProducts,
   getProductsStatic,
};
